﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using Domain.Model;
using Domain.Model.Interfaces;

using DataAccess.Utils;
using DataAccess.Exceptions;

using NHibernate;
using NHibernate.Engine;
using NHibernate.Criterion;

namespace DataAccess.Repositories
{
    public class SubprojectRepository : AbstractRepository<Subproject>, ISubprojectRepository
    {
        public SubprojectRepository() : 
            base(DataRepositoryException.SUBPROJECT_REPOSITORY, "subproject") { }

        public SubprojectTask GetTaskById(int taskId)
        {
            using (ISession session = SessionProvider.OpenSession())
            {
                try
                {
                    return session.Get<SubprojectTask>(taskId);
                }
                catch (Exception e)
                {
                    throw new DataRepositoryException(e.Message,
                        ExceptionType, "Could not get the SubprojectTask with the id: " + id);
                }
            }
        }

        public void DeleteSubprojectTask(SubprojectTask task)
        {
            using (ISession session = SessionProvider.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    try
                    {
                        ISQLQuery query = session.CreateSQLQuery("DELETE FROM SubprojectTasks WHERE Id = '" + task.Id + "'");
                        query.ExecuteUpdate();

                        session.Flush();
                        transaction.Commit();
                    }
                    catch (Exception e)
                    {
                        transaction.Rollback();

                        throw new DataRepositoryException(e.Message,
                            ExceptionType, "Could not delete task with the name: " + task.Name);
                    }
                }
            }
        }

        public void DeleteDetailFromSubprojects(string name)
        {
            using (ISession session = SessionProvider.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    try
                    {
                        ISQLQuery query = session.CreateSQLQuery("DELETE FROM SubprojectDetails WHERE Name = '" + name + "'");
                        query.ExecuteUpdate();

                        session.Flush();
                        transaction.Commit();
                    }
                    catch (Exception e)
                    {
                        transaction.Rollback();

                        throw new DataRepositoryException(e.Message,
                            ExceptionType, "Could not delete details with the name: " + name);
                    }
                }
            }
        }
    }
}